package DAO;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.JDBC;
import service.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class UserDao {
    //建立数据库连接

    public static Connection getConnection(){
        Connection conn=null;

        BeanFactory factory=new ClassPathXmlApplicationContext("begin.xml");
        JDBC jdbc=(JDBC)factory.getBean("jdbc");
        String url=jdbc.getUrl();
        String jdbcDriver=jdbc.getJdbcDriver();
        String user=jdbc.getUser();
        String password=jdbc.getPassword();
        try {
            System.out.println(jdbcDriver);
            Class.forName(jdbcDriver);
            conn = DriverManager.getConnection(url, user, password);
        }catch (Exception e){
            e.printStackTrace();
        }
         return conn;
    }
    public static int saveUser(User user){
        int i=0;
        try{
            Connection conn=UserDao.getConnection();
            String sql="insert into user(name,password) values(?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
           // ps.setInt(1,user.getId());
            ps.setString(1,user.getName());
            ps.setString(2,user.getPassword());
            i=ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }

}
